package com.team622.shop.orders.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.team622.shop.common.Result;
import com.team622.shop.common.exceptions.BusinessException;
import com.team622.shop.common.exceptions.enums.Resp;
import com.team622.shop.goods.feign.api.GoodsClient;
import com.team622.shop.goods.model.vo.GoodsListDetailsVO;
import com.team622.shop.orders.model.dto.CartDTO;
import com.team622.shop.orders.model.entity.Cart;
import com.team622.shop.orders.model.vo.CartItemVO;
import com.team622.shop.orders.service.handlers.BaseContextHandler;
import com.team622.shop.orders.service.mapper.CartMapper;
import com.team622.shop.orders.service.service.CartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车服务实现类
 * </p>
 *
 * @author team622
 * @since 2025-07-16
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    private final GoodsClient goodsClient;

    public CartServiceImpl(@Qualifier("com.team622.shop.goods.feign.api.GoodsClient") GoodsClient goodsClient) {
        this.goodsClient = goodsClient;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addCart(CartDTO cartDTO) {
        Cart cart = new Cart();
        BeanUtils.copyProperties(cartDTO, cart);
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getMemberId, cartDTO.getMemberId());
        wrapper.eq(Cart::getGoodsId, cartDTO.getGoodsId());
        //检查商品是否已经存在
        Cart item = this.getOne(wrapper);
        if (item != null) {
            item.setQuantity(item.getQuantity() + cartDTO.getQuantity());
            this.updateById(item);
            return;
        }

        //是一个新的条目，直接保存购物车项
        this.save(cart);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteCart() {
        Long memberId = BaseContextHandler.get();
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getMemberId, memberId);
        // 删除购物车项
        return this.remove(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Cart updateCart(CartDTO cartDTO) {
//        Cart cart = new Cart();
//        BeanUtils.copyProperties(cartDTO, cart);
//
//        // 更新购物车项
//        this.updateById(cart);
//        return cart;
        LambdaUpdateWrapper<Cart> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Cart::getMemberId, cartDTO.getMemberId())
                .eq(Cart::getGoodsId, cartDTO.getGoodsId())
                .set(Cart::getQuantity, cartDTO.getQuantity());

        boolean success = this.update(wrapper);
        if (!success) {
            log.error("更新购物车失败");
        }

        // 查询更新后的数据返回
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getMemberId, cartDTO.getMemberId())
                .eq(Cart::getGoodsId, cartDTO.getGoodsId());
        return this.getOne(queryWrapper);
    }

    @Override
    public List<CartItemVO> getCart() {
        Long memberId = BaseContextHandler.get();

        // 构建查询条件
        LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Cart::getMemberId, memberId);
        List<Cart> cartItems = this.list(queryWrapper);

        HashMap<Long, Integer> map=new HashMap<>();

        for (Cart cartItem : cartItems) {
            map.put(cartItem.getGoodsId(), cartItem.getQuantity());
        }

        Result<List<GoodsListDetailsVO>> goodsListDetailByIds = goodsClient.findGoodsListDetailByIds(cartItems.stream().map(Cart::getGoodsId).collect(Collectors.toList()));

        ArrayList<CartItemVO> cartItemVOS=new ArrayList<>();

        for (GoodsListDetailsVO item : goodsListDetailByIds.getData()) {
            CartItemVO cartItemVO=new CartItemVO();
            cartItemVO.setGoodsId(item.getId());
            cartItemVO.setGoodsName(item.getName());
            cartItemVO.setImageUrl(item.getImageUrl());
            cartItemVO.setPrice(item.getPrice());
            cartItemVO.setQuantity(map.get(item.getId()));
            cartItemVOS.add(cartItemVO);
        }

        // 查询会员购物车列表
        return cartItemVOS;
    }

    @Override
    public void reduceCart(CartDTO cartDTO) {
        Cart cart = new Cart();
        BeanUtils.copyProperties(cartDTO, cart);

        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getMemberId, cartDTO.getMemberId());
        wrapper.eq(Cart::getGoodsId, cartDTO.getGoodsId());
        //检查商品是否已经存在
        Cart item = this.getOne(wrapper);

        if (item == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }

        if (item.getQuantity() <= 1) {
            this.remove(wrapper);
        } else {
            item.setQuantity(item.getQuantity() - cartDTO.getQuantity());
            this.updateById(item);
        }

    }
}
